<template>
  <div class="directive-box">
    <div class="title-line list-caption mt15 ml10 relative">
      指令内容
      <div class="title-oper">
        <IconButton
          :icon="visible.content ? 'fold' : 'unfold'"
          :title="visible.content ? '收起' : '展开'"
          :activated="false"
          @click.native="handleModuleToggle('content')"
        ></IconButton>
      </div>
    </div>
    <div class="split-line mt18 mb18"></div>
    <Form class="custom-ivu-form ml40" ref="content_ref" :label-width="100" :model="formData" :rules="formRules">
      <FormItem label="指令编号：">
        <Input
          v-model="formData.ident"
          placeholder="按照规则自动生成（或者指令系统按照规则生成后同步回来显示）"
          clearable
          disabled
        ></Input>
      </FormItem>

      <FormItem label="指令标题：" prop="title" :title="formData.title">
        <Input
          placeholder="请输入指令标题（不超过100字）"
          clearable
          v-model="formData.title"
          :maxlength="100"
          :disabled="viewDetails.isDetails"
        ></Input>
      </FormItem>

      <FormItem label="指令来源：" class="d-inline-block mr30" prop="source">
        <Select
          v-model="formData.source"
          class="form-item--width"
          clearable
          :disabled="from === 'issue' || viewDetails.isDetails"
        >
          <Option v-for="(nt, i) of directiveSource" :key="i" :value="nt.key">{{ nt.value }}</Option>
        </Select>
      </FormItem>

      <FormItem label="上稿位置：" class="d-inline-block mr30" prop="location">
        <Select v-model="formData.location" class="form-item--width" clearable :disabled="viewDetails.isDetails">
          <Option v-for="(nt, i) of manuPosition" :key="i" :value="nt.key">{{ nt.value }}</Option>
        </Select>
        <Input
          v-show="formData.location === 'CUSTOM'"
          class="form-item--width ml10"
          placeholder="请输入上稿位置"
          clearable
          v-model="formData.customLocation"
          :maxlength="100"
          :disabled="viewDetails.isDetails"
        ></Input>
      </FormItem>

      <FormItem label="可视范围：" class="d-inline-block mr30" prop="visible">
        <Select v-model="formData.visible" class="form-item--width" clearable :disabled="viewDetails.isDetails">
          <Option v-for="(nt, i) of viewScope" :key="i" :value="nt.key">{{ nt.value }}</Option>
        </Select>
      </FormItem>

      <FormItem label="是否督办：" class="d-inline-block mr30" prop="supervisoryLen">
        <Select v-model="formData.supervisoryLen" class="form-item--width" clearable :disabled="viewDetails.isDetails">
          <Option v-for="(nt, i) of superviseOptions" :key="i" :value="nt.key">{{ nt.value }}</Option>
        </Select>
      </FormItem>

      <FormItem label="指令类型：" class="d-inline-block" prop="type">
        <Select
          v-model="formData.type"
          class="form-item--width"
          clearable
          :disabled="from === 'issue' || viewDetails.isDetails"
          @on-change="handleDirectiveTypeChange"
        >
          <Option v-for="(nt, i) of directiveType" :key="i" :value="nt.key">{{ nt.value }}</Option>
        </Select>
      </FormItem>

      <FormItem label="指令内容：" prop="content">
        <Input
          v-model="formData.content"
          type="textarea"
          style="height: 90px"
          placeholder="请输入"
          clearable
          :disabled="viewDetails.isDetails"
        ></Input>
      </FormItem>

      <FormItem label="上传附件：" prop="attachment">
        <div class="d-inline-block f14 upload-box">
          <Upload
            v-if="!viewDetails.isDetails"
            :before-upload="handleUpload"
            action=""
            class="d-inline-block"
            accept=".doc,.docx,.pdf,.rar,.zip"
          >
            <Button>选择文件</Button>
          </Upload>
          <span class="ml10">{{ formData.attachment || '未选择任何文件' }}</span>
          <!-- 新建 | 下发 的时候，不需要显示下载按钮 -->
          <template v-if="!['create', 'issue'].includes(from)">
            <a
              v-if="formData.attachment"
              :href="URL_attachment_dw + viewDetails.info.attachment.key"
              class="a-normalize ml14"
              download
            >
              下载
            </a>
          </template>
          <Icon
            v-show="formData.attachment && !viewDetails.isDetails"
            class="ml14 pointer f16"
            type="ios-close-circle-outline"
            @click="handleAttachmentRemove"
          />
        </div>
        <span v-if="!viewDetails.isDetails" class="ml20 f14">
          支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
        </span>
      </FormItem>

      <FormItem label="备注：">
        <Input
          v-model="formData.remark"
          :maxlength="200"
          type="textarea"
          style="height: 90px"
          placeholder="请输入"
          clearable
          :disabled="viewDetails.isDetails"
        ></Input>
      </FormItem>

      <!-- <Button style="display: none" type="primary" html-type="submit">查询</Button> -->
    </Form>
  </div>
</template>

<script>
// request
import { getGenerate_id } from '@/api/common/IssueDirective/index.js'
import { URL_attachment_dw } from '@/api/index.js'
// utils
import { cloneDeep } from '@/utils/uitls.js'
// service
import {
  createForm_content,
  createFormRules,
  // createPositionOptions,
  // createViewScopeOptions,
  createSuperviseOptions,
} from './service'
// vuex
import { createNamespacedHelpers } from 'vuex'
const { mapActions } = createNamespacedHelpers('manageEnd')
export default {
  name: 'DirectContent',

  props: {
    viewDetails: Object,
  },

  data() {
    return {
      formData: createForm_content(),
      formRules: createFormRules(this),
      // positionOptions: createPositionOptions(),
      // viewScopeOptions: createViewScopeOptions(),
      superviseOptions: createSuperviseOptions(),
      file: {},

      visible: {
        content: true,
      },

      URL_attachment_dw,
    }
  },

  computed: {
    from() {
      return this.$route.query.f
    },
    directiveSource() {
      return this.$store.getters['manageEnd/directiveSource']
    },
    manuPosition() {
      return this.$store.getters['manageEnd/manuPosition']
    },
    viewScope() {
      return this.$store.getters['manageEnd/viewScope']
    },
    directiveType() {
      return this.$store.getters['manageEnd/directiveType']
    },
  },

  watch: {
    viewDetails: {
      handler(v) {
        if (!v.isDetails) return
        const data = v.info
        for (let k in this.formData) {
          if (['source', 'type'].includes(k)) {
            this.formData[k] = data[k].key || ''
          } else if (k === 'attachment') {
            this.formData[k] = data[k].value || ''
          } else if (k === 'customLocation') {
            this.formData[k] = data['clocation']
          } else {
            this.formData[k] = data[k] || ''
          }
        }
      },
      deep: true,
    },

    directiveType(v) {
      if (!v || !v.length) return
      if (this.from === 'issue') {
        this.handleDirectiveTypeChange(this.formData.type)
      }
    },
  },

  methods: {
    ...mapActions(['getSources', 'getDirectiveTypes', 'getManuLocations', 'getVisibles']),

    handleUpload(file) {
      // console.log('file', file)
      // if (this.fileFormatIncludes.includes(file.name)) {
      //   this.$Message.error(`当前文件格式不支持，可选择的文件格式有：${this.fileFormatIncludes.join()}`)
      //   return
      // }
      this.file = file
      this.formData.attachment = file.name
      return false
    },

    handleAttachmentRemove() {
      this.formData.attachment = ''
      this.file = {}
    },

    handleDirectiveTypeChange(v) {
      this.$emit(
        'on-directive-type-Change',
        this.directiveType.find((it) => it.key === v),
      )
    },

    handleModuleToggle(module) {
      this.$parent.moduleHeightToggle(this, module)
    },

    handleFormSubmit(callback) {
      let promise
      // if no callback, return promise
      if (typeof callback !== 'function' && window.Promise) {
        promise = new window.Promise((resolve, reject) => {
          callback = function (valid) {
            resolve(valid)
          }
        })
      }

      this.$refs.content_ref.validate((valid) => {
        if (typeof callback === 'function') {
          callback(valid)
        }
      })

      return promise
    },

    getParams() {
      const data = cloneDeep(this.formData)
      if (this.file instanceof File) {
        data.file = this.file
      } else {
        data.file = ''
      }

      if (this.formData.location === 'CUSTOM') {
      } else {
        data.customLocation = ''
      }
      delete data.attachment

      return data
    },

    /* 生成指令编号 */
    async getGenerate_id() {
      const res = await getGenerate_id()
      this.formData.ident = res.data.data || ''
    },
  },

  mounted() {
    /* 不同的页面进入时，选中默认值 */
    if (this.from === 'issue') {
      this.formData.source = 'POSITIVE'
      this.formData.location = 'HOME'
      this.formData.visible = 'PUBLIC'
      this.formData.type = 'ARTICLE'
      /* 指令类型 在 watch 中触发事件 */
    } else if (this.from === 'create') {
      this.formData.source = 'CBC'
      this.formData.location = 'HOME'
      this.formData.visible = 'PUBLIC'
    }

    /* 详情不需要生成编号 */
    if (!this.viewDetails.isDetails) {
      this.getGenerate_id()
    }

    this.getManuLocations()
    this.getSources()
    this.getDirectiveTypes()
    this.getVisibles()
  },
}
</script>

<style lang="less" scoped>
.custom-ivu-form {
  /deep/ .ivu-form-item:last-of-type {
    margin-bottom: 0;
    padding-bottom: 10px;
  }
}
</style>
